import { showSuccessToast } from 'vant';
import { ref } from 'vue';

import { deserialize } from '@/plugins/reflect-metadata';
import type { ListState } from '@/types';

import { addWithdrawAccount, getWithdrawAccount, updateWithdrawAccount } from '../api';
import WithdrawAccountList, {
  WithdrawAccountConfig,
  WithdrawAccountItem,
} from '../models/WithdrawAccount';

const useWithdrawAccount = () => {
  const form = ref<any>({
    validate: () => Promise.resolve(),
  });
  const config = ref<WithdrawAccountConfig>(new WithdrawAccountConfig());

  const state = ref<ListState<WithdrawAccountItem>>({
    data: [],
    total: 0,
    loading: false,
  });

  const fetchData = async () => {
    try {
      state.value.loading = true;
      const { data } = await getWithdrawAccount();
      const resultData = deserialize(data, WithdrawAccountList);
      state.value.data = resultData.data;
      state.value.total = resultData.total;
    } catch (error) {
      //
    } finally {
      state.value.loading = false;
    }
  };

  const handleAdd = async () => {
    try {
      state.value.loading = true;
      await form.value.validate();
      const { data } = await addWithdrawAccount(config.value);
      showSuccessToast(data.msg || '添加成功');
    } catch (error) {
      //
    } finally {
      state.value.loading = false;
    }
  };

  const handleUpdate = async () => {
    try {
      state.value.loading = true;
      await form.value.validate();
      const { data } = await updateWithdrawAccount(config.value);
      showSuccessToast(data.msg || '更新成功');
    } catch (error) {
      //
    } finally {
      state.value.loading = false;
    }
  };

  return {
    config,
    state,
    fetchData,
    handleAdd,
    handleUpdate,
    form,
  };
};

export default useWithdrawAccount;
